package com.txd.mofa;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.kongzue.baseframework.BaseFragment;
import com.kongzue.baseframework.interfaces.Layout;
import com.kongzue.baseframework.util.JumpParameter;
import com.kongzue.baseframework.util.OnPermissionResponseListener;
import com.kongzue.baseframework.util.Preferences;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.ninetaildemonfox.zdl.ninetails.map.JSONUtils;
import com.txd.mofa.base.BaseAty;
import com.txd.mofa.fabu.aty.FabuAty;
import com.txd.mofa.fabu.aty.PaizhaoAty1;
import com.txd.mofa.net.NetUtils;
import com.txd.mofa.shoucang.fgt.ShoucangFgt;
import com.txd.mofa.shouye.fgt.HomeFgt;
import com.txd.mofa.fenlei.fgt.SousuoFgt;
import com.txd.mofa.utils.UpdateService;
import com.txd.mofa.view.GengxinDialog;
import com.txd.mofa.view.NoSlidingViewPager;
import com.txd.mofa.view.ViewPagerAdapter;
import com.txd.mofa.wode.fgt.WoFgt;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import baseokhttp3.OkHttpClient;
import baseokhttp3.Request;
import baseokhttp3.Response;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Layout(R.layout.activity_main)
public class MainActivity extends BaseAty {

    RelativeLayout llFabu;
    private NoSlidingViewPager viewPager;
    private RadioGroup aty_main_rg;
    private List<BaseFragment> fragemnts = new ArrayList<>();
    private RadioButton shouye,shequ,shoucang,wode;
    private int i;
    private Map<String, String> data;
    private ImageView iv_tou;

    @Override
    public void initViews() {
        super.initViews();
        iv_tou = findViewById(R.id.iv_tou);
        llFabu = findViewById(R.id.ll_fabu);
        viewPager = findViewById(R.id.viewpager);
        aty_main_rg = findViewById(R.id.aty_main_rg);
        shequ = findViewById(R.id.shequ);
        shoucang = findViewById(R.id.shoucang);
        shouye = findViewById(R.id.shouye);
        wode = findViewById(R.id.wode);

        i = packageCode(me);

        http();

    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {
    }

    @Override
    protected void onNetworkDisConnected() {
    }

    @Override
    public void initDatas(JumpParameter paramer) {



        fragemnts.add(HomeFgt.newInstance());
        fragemnts.add(SousuoFgt.newInstance());
        fragemnts.add(ShoucangFgt.newInstance());
        fragemnts.add(WoFgt.newInstance());


        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragemnts);
        viewPager.setAdapter(viewPagerAdapter);
        viewPager.setOffscreenPageLimit(fragemnts.size());

        /**
         * 设置与viewpager关联
         */
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        aty_main_rg.check(R.id.shouye);
                        break;
                    case 1:
                        aty_main_rg.check(R.id.shequ);
                        break;
                    case 2:
                        aty_main_rg.check(R.id.shoucang);
                        EventBus.getDefault().post(new Shuaxin("1"));
                        break;
                    case 3:
                        aty_main_rg.check(R.id.wode);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });

        /**
         * 点击按钮切换界面
         */
        aty_main_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.shouye:
                        viewPager.setCurrentItem(0, true);
                        break;
                    case R.id.shequ:
                        viewPager.setCurrentItem(1, true);
                        break;
                    case R.id.shoucang:
                        viewPager.setCurrentItem(2, true);
                        EventBus.getDefault().post(new Shuaxin("1"));
                        break;
                    case R.id.wode:
                        viewPager.setCurrentItem(3, true);
                        break;
                    default:
                }
            }
        });


    }

    public static int packageCode(Context context) {
        PackageManager manager = context.getPackageManager();
        int code = 0;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            code = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return code;
    }

    @Override
    protected void onResume() {
        super.onResume();

        requestPermission(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, new OnPermissionResponseListener() {
            @Override
            public void onSuccess(String[] permissions) {
            }

            @Override
            public void onFail() {
            }
        });


        if (Preferences.getInstance().getString(me,"face_img","face_img").equals("") ||
                Preferences.getInstance().getString(me,"face_img","face_img") == null){
            iv_tou.setVisibility(View.GONE);
        }else {
            iv_tou.setVisibility(View.VISIBLE);
            Glide.with(me).load(Preferences.getInstance().getString(me,"face_img","face_img")).into(iv_tou);
        }

    }

    private void http() {
        HttpRequest.POST(me, updateAndroid, new Parameter(), new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                if (error == null) {
                    Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                    if (map.get("code").equals("1")){
                        data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                        if (Integer.parseInt(data.get("versionCode")) > i){

                            GengxinDialog dialog = new GengxinDialog(me, data,new GengxinDialog.SignListener() {
                                @Override
                                public void shengji() {

                                    requestPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new OnPermissionResponseListener() {
                                        @Override
                                        public void onSuccess(String[] permissions) {

                                            UpdateService updateService = new UpdateService(me);
                                            updateService.download(data.get("url"),System.currentTimeMillis()+".apk");

                                        }

                                        @Override
                                        public void onFail() {

                                        }
                                    });

                                }
                            });
                            dialog.show();
                        }
                    }
                }else {
                    toast("网络异常");
                }
            }
        });
    }

    @Override
    public void setEvents() {

        llFabu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump(FabuAty.class);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }



    private long firstPressedTime;
    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - firstPressedTime < 2000) {
            toast("欢迎下次再来");
            super.onBackPressed();
        } else {
            toast("再按一次退出");
            firstPressedTime = System.currentTimeMillis();
        }
    }

}
